package com.borqs.samples.developer;

import java.util.HashMap;

import com.borqs.samples.DBHelper;
import com.borqs.samples.DBProvider;
import com.borqs.samples.DBProvider.DeveloperTable;
import com.borqs.samples.DBProvider.SessionsTable;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class DeveloperContentProvider extends ContentProvider {

    private static HashMap<String, String> mDeveloperProjectionMap;

    private static final int DEVELOPER = 1;
    private static final int DEVELOPER_ID = 2;

    private static final UriMatcher mUriMatcher;

    private DBHelper mOpenHelper;

    @Override
    public boolean onCreate() {
        mOpenHelper = new DBHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        String orderBy;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理

        case DEVELOPER_ID:
            qb.appendWhere(DBProvider.DeveloperTable._ID + "=?");
            selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
                    new String[] { uri.getLastPathSegment() });
        case DEVELOPER:
            qb.setTables(DBProvider.DeveloperTable.TABLE_NAME);
            qb.setProjectionMap(mDeveloperProjectionMap);
            if (TextUtils.isEmpty(sortOrder)) {
                orderBy = DBProvider.DeveloperTable.DEFAULT_SORT_ORDER;
            } else {
                orderBy = sortOrder;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
                null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;

    }

    @Override
    public String getType(Uri uri) {
        switch (mUriMatcher.match(uri)) {
        case DEVELOPER:
            return DBProvider.CONTENT_TYPE;
        case DEVELOPER_ID:
            return DBProvider.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentvalues) {
        ContentValues values = null;
        String tableName = "";
        String nullColumn = "";

        if (null != contentvalues) {
            values = new ContentValues(contentvalues);
        } else {
            values = new ContentValues();
        }

        switch (mUriMatcher.match(uri)) {
        case DEVELOPER:
            tableName = DBProvider.DeveloperTable.TABLE_NAME;
            break;
        default:
            break;
        }
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(tableName, null, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(uri, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }
        throw new SQLException("Failed to insert row into " + uri);

    }

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String finalWhere;
        int count;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理，注意下面用到的表名不要弄错了
        case DEVELOPER:
            count = db.delete(DBProvider.DeveloperTable.TABLE_NAME, where,
                    whereArgs);
            break;

        case DEVELOPER_ID:
            finalWhere = DatabaseUtils.concatenateWhere(
                    DBProvider.DeveloperTable._ID + " = "
                            + ContentUris.parseId(uri), where);
            count = db.delete(DBProvider.DeveloperTable.TABLE_NAME, finalWhere,
                    whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    static {
        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        mUriMatcher.addURI(DBProvider.SessionsTable.AUTHORITY,
                DBProvider.DeveloperTable.TABLE_NAME, DEVELOPER);
        mUriMatcher.addURI(DBProvider.SessionsTable.AUTHORITY,
                DBProvider.DeveloperTable.TABLE_NAME + "/#", DEVELOPER_ID);

        mDeveloperProjectionMap = new HashMap<String, String>();
        mDeveloperProjectionMap.put(DBProvider.DeveloperTable._ID,
                DBProvider.DeveloperTable._ID);
        mDeveloperProjectionMap.put(DBProvider.DeveloperTable.TIME,
                DBProvider.DeveloperTable.TIME);
        mDeveloperProjectionMap.put(DBProvider.DeveloperTable.WIFI_SATE,
                DBProvider.DeveloperTable.WIFI_SATE);
        mDeveloperProjectionMap.put(DBProvider.DeveloperTable.GPS_SATE,
                DBProvider.DeveloperTable.GPS_SATE);
        mDeveloperProjectionMap.put(DBProvider.DeveloperTable.SYNC_SATE,
                DBProvider.DeveloperTable.SYNC_SATE);
        mDeveloperProjectionMap.put(DBProvider.DeveloperTable.AIRPLANE_STATE,
                DBProvider.DeveloperTable.AIRPLANE_STATE);
        mDeveloperProjectionMap.put(DBProvider.DeveloperTable.START_VELOCITY,
                DBProvider.DeveloperTable.START_VELOCITY);
    }

}
